﻿using System.Linq;
using System.Reflection;
using Infrastructure;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using XieAuth.App.Interface;

namespace XieAuth.WebApi.Filters
{
    public class ApiAuthFilter : IActionFilter
    {
        private readonly IAuth _authUtil;

        public ApiAuthFilter(IAuth authUtil)
        {
            _authUtil = authUtil;
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var description =
                (Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor;

            //var Controllername = description.ControllerName.ToLower();
            //var Actionname = description.ActionName.ToLower();

            //添加有允许匿名的Action，可以不用登录访问，如Login/Index
            //var anonymous = description.MethodInfo.GetCustomAttribute(typeof(AllowAnonymousAttribute));
            //if (anonymous != null)
            //{
            //    return;
            //}
            //添加有允许匿名的Action，可以不用登录访问，如Login/Index
            if (description.MethodInfo.GetCustomAttributes(typeof(AllowAnonymousAttribute), true).Length != 0 || description.ControllerTypeInfo.GetCustomAttributes<AllowAnonymousAttribute>(true).Count() != 0)
            {
                return;
            }

            if (!_authUtil.CheckLogin())
            {
                context.HttpContext.Response.StatusCode = 401;
                context.Result = new JsonResult(new DtoResult
                {
                    Code = 401,
                    Message = "认证失败，请提供认证信息"
                });
            }
        }

        public void OnActionExecuted(ActionExecutedContext context)
        {
            return;
        }
    }
}
